import requests
import pandas as pd
from datetime import datetime, timedelta


# 获取数据
def get_weather_data(api_key, lat, lon, start_date, end_date):
    base_url = "https://api.weatherbit.io/v2.0/history/hourly"
    weather_data = []

    start = datetime.strptime(start_date, '%Y-%m-%d')
    end = datetime.strptime(end_date, '%Y-%m-%d')

    while start < end:
        end_date_part = start + timedelta(days=1)
        if end_date_part > end:
            end_date_part = end

        params = {
            'lat': lat,
            'lon': lon,
            'start_date': start.strftime('%Y-%m-%d'),
            'end_date': end_date_part.strftime('%Y-%m-%d'),
            'tz': 'local',
            'key': api_key
        }
        response = requests.get(base_url, params=params)

        if response.status_code == 200:
            data = response.json()
            for hour_data in data['data']:
                weather_data.append({
                    'date': datetime.strptime(hour_data['timestamp_local'], '%Y-%m-%dT%H:%M:%S'),
                    'temperature': hour_data['temp']
                })
        else:
            print(f"API请求失败，状态码：{response.status_code}，响应内容：{response.text}")

        start = end_date_part

    return pd.DataFrame(weather_data)


# API密钥和位置
API_KEY = '****************************'
LAT = 30.924  # 孝感市孝南区纬度
LON = 113.910  # 孝感市孝南区经度
START_DATE = '2023-01-01'
END_DATE = '2023-05-31'  # 获取更多天数的数据

weather_df = get_weather_data(API_KEY, LAT, LON, START_DATE, END_DATE)
if not weather_df.empty:
    weather_df.to_csv('temperature_data.csv', index=False)
    print("数据已成功写入 'temperature_data.csv'")
    print(weather_df.head())
else:
    print("未获取到数据，请检查API请求和密钥。")
